package com.example.timetracker;

import persistencia.TimeTrackerDatabaseHelper;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;

public class MainActivity extends Activity {
	TimeTrackerAdapter timeTrackerAdapter;
	private TimeTrackerDatabaseHelper databaseHelper;
	
	public static final int TIME_ENTRY_REQUEST_CODE = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		databaseHelper = new TimeTrackerDatabaseHelper(this);
		
		ListView listView = (ListView) findViewById(R.id.timesList);
		timeTrackerAdapter = new TimeTrackerAdapter();
		listView.setAdapter(timeTrackerAdapter);
		
		refreshTimeRecordList();
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.time_list_menu, menu);
		return true;
	}
	
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		super.onMenuItemSelected(featureId, item);
		if (item.getItemId() == R.id.addTime){
			Intent intent = new Intent(this, AddTimeActivity.class);
			startActivityForResult(intent, TIME_ENTRY_REQUEST_CODE);
			return true;
		}
		if (item.getItemId() == R.id.about_menu_item) {
			Intent intent = new Intent(this, AboutActivity.class);
			startActivity(intent);
			
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if (requestCode == TIME_ENTRY_REQUEST_CODE){
			if(resultCode == RESULT_OK){
				String notes = data.getStringExtra("notes");
				String time = data.getStringExtra("time");
				
				TimeRecord timeRecord = new TimeRecord(time, notes);
				databaseHelper.saveTimeRecord(timeRecord);
				
				refreshTimeRecordList();
			}
		}
	}
	
	public void refreshTimeRecordList() {
		timeTrackerAdapter.setListTimes(databaseHelper.getTimeRecordList());
		timeTrackerAdapter.notifyDataSetChanged();
	}
	
		
}
